from django.shortcuts import render
from orders.models import OrderInfo
from django import http
from alipay import AliPay
from django.conf import settings
import os

from meiduo_mall.utils.login_user import LoginUserView
from meiduo_mall.utils.response_code import RETCODE
from .models import Payment


class PaymentView(LoginUserView):
    """支付"""

    def get(self, request, order_id):
        # 校验参数
        try:
            order = OrderInfo.objects.get(user=request.user, order_id=order_id,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('订单有误')
        """
        ALIPAY_APPID = '2016091900551154'
        ALIPAY_DEBUG = True  # 表示是沙箱环境还是真实支付环境
        ALIPAY_URL = 'https://openapi.alipaydev.com/gateway.do'
        ALIPAY_RETURN_URL = 'http://www.meiduo.site:8000/payment/status/'
        """
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )
        # 调用函数得到链接查询参数
        data_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=settings.ALIPAY_APPID, # 美多订单编号
            total_amount=str(order.total_amount),
            subject='美多商城%s'%order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )
        # 拼接链接
        # 沙箱环境 'https://openapi.alipaydev.com/gateway.do'
        # 真实开发环境 'https://openapi.alipay.com/gateway.do'
        alipay_url = settings.ALIPAY_URL + '?' + data_string
        # 响应
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK','alipay_url':alipay_url})


class PaymentStatusView(LoginUserView):
    """验证支付结果"""
    def get(self,request):
        # 获取查询参数
        query_dict = request.GET
        # 将查询参数转化为字典
        data = query_dict.dict()
        # 移除sign并返回
        sign = data.pop('sign') # 移除sign后加密的data
        # 创建alipay实例对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )
        # 调用verify验证
        success = alipay.verify(data,sign)
        # 判断验证结果及响应
        if success:
            # 获取美多订单编号和支付宝交易号存表
            order_id = data.get('order_id')
            trade_id = data.get('trade_id')
            try:
                # 判断payment表中是否存在该订单
                Payment.objects.get(trade_id=trade_id)
            except Payment.DoesNotExist:
                # 不存在创建数据
                Payment.objects.create(order_id=order_id,trade_id=trade_id)
            # 修改订单表中status
            OrderInfo.objects.filter(user=request.user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
            return render(request,'pay_success.html',{'trade_id':trade_id})
        else:
            return http.HttpResponseForbidden('无效的请求')